'use strict';
import React from 'react'
import { View, ScrollView, Text, Image, TouchableOpacity, AsyncStorage } from 'react-native'
import { Metrics, Colors, Fonts } from '../Themes'
import { API, WINDOW } from '../Services'
import styles from './Styles/CommonContainerStyles'
import { StackActions } from '@react-navigation/native'
import moment from 'moment'
import momentLocale from 'moment/locale/zh-cn';
moment.updateLocale('zh-cn', momentLocale);
import {
    Menu,
    MenuOptions,
    MenuOption,
    MenuTrigger,
} from 'react-native-popup-menu';


class DevicesHomeScreen extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            isShowingText: moment().format('HH:mm:ss'),
            sensorData: [],
            checkReslut: 'false',
        }
        setInterval(() => {
            this.setState(previousState => {
                return { isShowingText: moment().format('HH:mm:ss') };
            });
        }, 1000);
    }

    componentDidMount() {
        this.fetchData()
        this._fetch_checkCtrlSet()
    }

    logout() {
        const { dispatch } = this.props.navigation
        AsyncStorage.removeItem('loginUser', (error) => {
            WINDOW.showToast('退出登录成功！')
            this.relieveLoginName()
            dispatch(
                StackActions.replace('Login')
            )
        })
    }

    relieveLoginName() {
        API.relieveLoginName(WINDOW.__data.loginUser.userid)
    }

    fetchData() {
        API.getDetailsInfoBySceneId(this.props.route.params.sceneId).then((response) => {
            const { ok, resultMessage, data } = response
            if (ok) {
                console.log(data)
                this.setState({ ...data })
            } else {
                return WINDOW.showToast(resultMessage)
            }
        })
    }

    _fetch_checkCtrlSet() {
        API.checkCtrlSet(this.props.route.params.sceneId).then((response) => {
            const { ok, data } = response
            if (ok) {
                this.setState({ checkReslut: data.checkReslut })
            }
        })
    }

    _getValue(value, type) {
        let firstColor = '#3ACD89'
        let secondColor = '#FCA920'
        let thirdColor = '#EA3767'
        let resultValue
        let resultVColor
        switch (type) {
            case 1:
                if (value >=18 && value <= 23) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if ((value >=8 && value <= 18) || (value >=23 && value <= 28)) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }

                break;
            case 2:
                if (value >=30 && value <= 80) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if ((value >=20 && value <= 30) || (value >=80 && value <= 90)) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            case 7:
                if (value <= 1000) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if (value >=1000 && value <= 2000) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            case 8:
                if (value <= 0.1) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if (value >=0.1 && value <= 0.15) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            case 12:
                if (value <= 35) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if (value >=35 && value <= 75) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            case 14:
                if (value <= 0.08) {
                    resultValue = '优'
                    resultVColor = firstColor
                } else if (value >=0.08 && value <= 0.2) {
                    resultValue = '良'
                    resultVColor = secondColor
                } else {
                    resultValue = '差'
                    resultVColor = thirdColor
                }
                break;
            default:
                break;
        }
        return { resultValue, resultVColor }
    }

    _onClick(item) {
        this.props.navigation.navigate('DevicesChart', { item, sceneId: this.props.route.params.sceneId })
    }

    _renderItem(element, index) {
        const {resultValue, resultVColor} = this._getValue(element.value, element.sensorType)
        let resultImage
        let textColor
        if (resultValue === '优') {
            resultImage = require('../Images/you.png')
            textColor = 'black'
        } else if (resultValue === '良') {
            resultImage = require('../Images/yb.png')
            textColor = resultVColor
        } else {
            resultImage = require('../Images/zd.png')
            textColor = resultVColor
        }
        return (
            <TouchableOpacity key={index} onPress={() => this._onClick(element)} style={{ width: 200, backgroundColor: Colors.lightGrayColor, marginTop: 15, borderRadius: 10, alignItems: 'center', alignSelf: 'center', marginHorizontal:30 }}>
                <Text style={{ fontSize: 25, color: 'black', marginTop: 20 }}>{element.sensorName}</Text>
                <Text style={{ fontSize: 16, color: textColor, marginTop: 5 }}>（{element.unit}）</Text>
                <Text style={{ fontSize: 50, fontWeight: 'bold', color: 'black', marginTop: 30 }}>{element.value}</Text>
                <View style={{ marginTop: 30, flexDirection: 'row', alignItems: 'center', alignSelf: 'center', }}>
                    <Image source={resultImage} style={{ tintColor: '#47496D' }} /> 
                    <Text style={{ fontSize: 30, color: Colors.graytextColor, marginLeft: 5 }}>{resultValue}</Text>
                </View>
                <View style={{ width: '90%', height: 8, marginTop: 20, marginBottom: 8, borderRadius: 4, backgroundColor: resultVColor }} />
            </TouchableOpacity>
        )
    }

    render() {
        return (
            <View style={styles.container}>
                <Image source={require('../Images/bg_home.png')} style={{ width: '100%', height: '100%', position: 'absolute' }} resizeMode='stretch' />
                <View style={{ flex: 1, justifyContent:'center',alignItems:'flex-start'}}>
                    <Menu onSelect={value => {
                        switch (value) {
                            case 1:
                                this.props.navigation.navigate('DeviceRule', { ...this.props.route.params })
                                break;
                            case 2:
                                this.props.navigation.navigate('DevicesSet', { sceneId: this.props.route.params.sceneId })
                                break;
                            case 3:
                                this.props.navigation.goBack()
                                break;
                            case 4:
                                this.logout()
                                break;
                            default:
                                break;
                        }
                    }} style={{ position: 'absolute', right: 50, top: 40 }}>
                        <MenuTrigger>
                            <Image source={require('../Images/icon_mssd.png')} />
                        </MenuTrigger>
                        <MenuOptions>
                            <MenuOption value={1} >
                                <Text style={{ fontSize: 20, margin: 10 }}>规则设置</Text>
                            </MenuOption>
                            {this.state.checkReslut === 'ture' ?
                                <MenuOption value={2} >
                                    <Text style={{ fontSize: 20, margin: 10 }}>控制设置</Text>
                                </MenuOption> : null
                            }
                            {this.props.route.params.hideBack ? null 
                            :
                            <MenuOption value={3} >
                                <Text style={{ fontSize: 20, margin: 10 }}>切换场景</Text>
                            </MenuOption>
                            }
                            <MenuOption value={4} >
                                <Text style={{ fontSize: 20, margin: 10 }}>退出登录</Text>
                            </MenuOption>
                        </MenuOptions>
                    </Menu>

                    <View style={{ marginLeft:'10%'}}>
                        <Text style={{ fontSize: 50, color: 'white' }}>{moment().format('YYYY年MM月Do   ddd')}</Text>
                        <Text style={{ fontSize: 120, fontWeight: 'bold', color: 'white', marginBottom: 60, marginTop: 30, textAlignVertical: 'bottom' }}>{this.state.isShowingText}</Text>
                    </View>
                    {/* <View style={{ justifyContent: 'center', alignItems: 'center', marginRight: 80 }}>
                        <Image source={require('../Images/tq.png')} />
                        <Text style={{ fontSize: 40, color: 'white', marginTop: 15 }}>15-18</Text>
                        <Text style={{ fontSize: 40, color: 'white', marginTop: 5 }}>晴转多云</Text>
                    </View> */}
                </View>
                <ScrollView style={{flex:1,alignSelf:'center'}} horizontal={true} showsHorizontalScrollIndicator={false}>
                    {this.state.sensorData.map((element, index) => this._renderItem(element, index))}
                </ScrollView>
            </View>
        )
    }
}

export default DevicesHomeScreen
